/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.DccrDAO;
import com.cashmate.hibernate.pojo.Branches;
import com.cashmate.hibernate.pojo.Dccr;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.utilities.Utils;
import com.opensymphony.xwork2.ActionSupport;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;

/**
 *
 * @author Dean
 */
@Result(name = "error", type = "redirectAction", location = "../error/messages.jsp")
public class ForGridSelectMonth extends ActionSupport {

    private Logger logger = Logger.getLogger(ForGridSelectMonth.class);
    private Map<String, String> monthMap;
    private final Branches b = (Branches) ServletActionContext.getRequest().getSession().getAttribute("branch");
    private final DccrDAO dccrdao = (DccrDAO) ServletActionContext.getServletContext().getAttribute("dccrDAO");
    private String forPie;

    public void setForPie(String forPie) {
        this.forPie = forPie;
    }

    public Map<String, String> getMonthMap() {
        return monthMap;
    }

    @Action(value = "/select-month", results = {
        @Result(name = "success", type = "json")
    })
    @Override
    public String execute() throws Exception {
        try {
            DetachedCriteria criteria = DetachedCriteria.forClass(Dccr.class);
            monthMap = new HashMap<String, String>();

            if (b.getBranchid() == 1 && (forPie == null || forPie.equals("false"))) {
                criteria.add(Restrictions.eq("isactive", true));

                ProjectionList pl = Projections.projectionList();
                pl.add(Projections.property("dategenerated"));
                pl.add(Projections.property("branchcode"));
                pl.add(Projections.property("branchid"));

                criteria.setProjection(Projections.distinct(pl));
                criteria.addOrder(Order.desc("dategenerated"));
                criteria.addOrder(Order.asc("branchid"));

                List result = dccrdao.findProjectedCriteria(criteria);

                criteria.setProjection(null);

                for (Object r : result) {
                    Object[] obj = (Object[]) r;
                    DateTime dt = Utils.stringArrToDateTime(obj[0].toString().split("/"));
                    String key = Utils.prefixZero(dt.getMonthOfYear()) + "-" + dt.getYear() + "-" + obj[2].toString();
                    if (!monthMap.containsKey(key) && Utils.isCutOff(dt)) {
                        monthMap.put(key, obj[1].toString() + " - " + dt.monthOfYear().getAsShortText() + " " + dt.getYear());
                    }
                }

                if (monthMap.size() < 1) {
                    monthMap.put("-1", "Empty");
                }
            } else if (b.getBranchid() != 1 || forPie.equals("true")) {
                criteria.add(Restrictions.eq("isactive", true));
                if (forPie != null) {
                    if (!forPie.equals("true")) {
                        criteria.add(Restrictions.eq("branchid", b.getBranchid()));
                    }
                }
                ProjectionList pl = Projections.projectionList();
                pl.add(Projections.property("dategenerated"));
                pl.add(Projections.property("branchcode"));
                pl.add(Projections.property("branchid"));

                criteria.setProjection(Projections.distinct(pl));
                criteria.addOrder(Order.desc("dategenerated"));
                criteria.addOrder(Order.asc("branchid"));

                List result = dccrdao.findProjectedCriteria(criteria);

                criteria.setProjection(null);

                for (Object r : result) {
                    Object[] obj = (Object[]) r;
                    DateTime dt = Utils.stringArrToDateTime(obj[0].toString().split("/"));
                    String key = Utils.prefixZero(dt.getMonthOfYear()) + "-" + dt.getYear() + "-" + obj[2].toString();
                    if (!monthMap.containsKey(key) && Utils.isCutOff(dt)) {
                        monthMap.put(key, dt.monthOfYear().getAsShortText() + " " + dt.getYear());
                    }
                }

                if (monthMap.size() < 1) {
                    monthMap.put("-1", "Empty");
                }
            }
        } catch (Exception ex) {
            Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
            if (emps != null) {
                logger.fatal("(" + emps.getIdnumber() + "):" + ex.getLocalizedMessage(), ex);
            } else {
                logger.fatal(ex.getLocalizedMessage(), ex);
            }
            addActionError(ex.getLocalizedMessage());
            return ERROR;
        } finally {
            DccrDAO.close();
        }
        return SUCCESS;
    }
}
